package com.yc.multiple.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {OrderDataSourceConfig.BASE_PACKAGES},
        sqlSessionFactoryRef = OrderDataSourceConfig.SQL_SESSIONFACTORY_REF,
        sqlSessionTemplateRef = OrderDataSourceConfig.SQL_SESSIONTEMPLATE_REF)
public class OrderDataSourceConfig {

    static final String BASE_PACKAGES="com.yc.multiple.dao.order";
    static final String SQL_SESSIONFACTORY_REF="orderSqlSessionFactory";
    static final String SQL_SESSIONTEMPLATE_REF="orderSqlSessionTemplate";
    static final String MAPPERLOCATIONS="classpath:mapper/order/*.xml";

    @Bean
    @ConfigurationProperties("spring.datasource.order")
    public DataSource orderDataSource(){
        return new HikariDataSource();
    }

    @Bean
    public SqlSessionFactory orderSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(orderDataSource());
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MAPPERLOCATIONS));
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate orderSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(orderSqlSessionFactory());
        return template;
    }
}
